<template>
  <div class="currencyItem">
    <!-- 左侧币种信息 -->
    <div class="left">
      <image-load 
        :filePath="currencyItem.logo" 
        class="leftImg" 
        v-if="showLeftImg && currencyItem.logo"
      />
      <div class="coin-info">
        <div class="textTop fw-num">
          {{ currencyItem.showSymbol || currencyItem.coin }}
        </div>
      </div>
    </div>

    <!-- 中间折线图（优化波动） -->
    <div class="chart-container">
      <svg :width="80" :height="40" class="trend-chart">
        <path 
          :d="generatePath" 
          :stroke="trendColor"
          stroke-width="1.8" 
          fill="none"
          stroke-linecap="round"
        />
      </svg>
    </div>

    <!-- 右侧价格信息（立即更新） -->
    <div class="right">
      <div class="price-box">
        <div class="fw-num price-text">
          {{ priceFormat(currentPrice) }}
        </div>
        <div :class="[changeDirection, 'change-text']">
          {{ priceChangePercent }}%
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onBeforeUnmount } from 'vue'
import { useTradeStore } from '@/store/trade'
import { priceFormat } from '@/utils/decimal.js'

const tradeStore = useTradeStore()
const points = ref([])
let timer = null

// 增强波动参数配置
const WAVE_CONFIG = {
  amplitude: 25,   // 波动幅度 (+50%)
  frequency: 2.5,  // 波动频率 (+25%)
  speed: 600,      // 更新速度 (原1800-3000ms)
  points: 6        // 数据点数量 (-25%)
}

const props = defineProps({
  currencyItem: {
    type: Object,
    default: () => ({
      logo: '',
      showSymbol: '',
      coin: 'BTC',
      volume: 0
    })
  },
  showLeftImg: {
    type: Boolean,
    default: true
  }
})

// 实时价格计算（响应速度优化）
// const currentPrice = computed(() => {
//   const priceInfo = tradeStore.allCoinPriceInfo[props.currencyItem.coin]
//   return Number(priceInfo?.close || tradeStore.klineTicker?.close || 0)
// })

const currentPrice = computed(() => {
  return Number(
    tradeStore.klineTicker?.close ??  // 严格使用空值合并
    tradeStore.allCoinPriceInfo[props.currencyItem.coin]?.close ?? 
    0
  )
})

// const openPrice = computed(() => {
//   const priceInfo = tradeStore.allCoinPriceInfo[props.currencyItem.coin]
//   return Number(priceInfo?.openPrice || tradeStore.klineTicker?.open || 0)
// })

const openPrice = computed(() => {
  return Number(
    tradeStore.klineTicker?.open ??   // 严格使用空值合并
    tradeStore.allCoinPriceInfo[props.currencyItem.coin]?.openPrice ?? 
    0
  )
})

// 立即计算涨跌幅
const priceChangePercent = computed(() => 
  ((currentPrice.value - openPrice.value) / openPrice.value * 100 || 0).toFixed(2)
)

// 动态颜色计算（取消过渡）
const changeDirection = computed(() => 
  currentPrice.value >= openPrice.value ? 'rise' : 'fall'
)

const trendColor = computed(() => 
  changeDirection.value === 'rise' ? '#FF4444' : '#00CC66'
)

// 高频波动生成器
const generateDynamicWave = (prev = []) => {
  const lastValue = prev.length ? prev[prev.length-1] : Math.random() * 30 + 10
  return Array.from({length: WAVE_CONFIG.points}, (_, i) => {
    const base = lastValue + 
      Math.sin(i * WAVE_CONFIG.frequency) * WAVE_CONFIG.amplitude +
      Math.cos(i * WAVE_CONFIG.frequency * 0.8) * WAVE_CONFIG.amplitude * 0.7
    
    return Math.max(5, Math.min(50, 
      base + (Math.random() - 0.5) * WAVE_CONFIG.amplitude * 0.6
    ))
  })
}

// 启动波动引擎
const startWaveEngine = () => {
  points.value = generateDynamicWave(points.value)
  timer = setTimeout(startWaveEngine, WAVE_CONFIG.speed + Math.random() * 300)
}

// 路径生成（性能优化）
const generatePath = computed(() => {
  if(points.value.length < 2) return 'M0 20 L80 20'
  
  return points.value.map((value, index) => {
    const x = (index * 80) / (points.value.length - 1)
    const y = 40 - ((value - 5) / 45 * 35) // 动态缩放
    return `${index === 0 ? 'M' : 'L'} ${x} ${y.toFixed(2)}`
  }).join(' ')
})

onMounted(startWaveEngine)
onBeforeUnmount(() => clearTimeout(timer))

</script>

<style lang="scss" scoped>
.currencyItem {
  padding: 12px 15px;
  transition: none; /* 取消容器过渡 */

  .trend-chart {
    transform: scaleY(0.7) translateY(2px);
    transition: none !important; /* 取消路径过渡 */
    will-change: transform;
  }

  .price-text {
    font-size: 14px;
    transition: none; /* 价格立即变化 */
  }

  .change-text {
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 3px;
    transition: none; /* 颜色立即变化 */
  }

  .rise {
    background: rgba(255, 68, 68, 0.12);
    color: #FF4444;
  }

  .fall {
    background: rgba(0, 204, 102, 0.12);
    color: #00CC66;
  }
}
</style>